package com.tjetc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.tjetc.dao.UserMapper;
import com.tjetc.domain.dto.UserDTO;
import com.tjetc.domain.po.User;
import com.tjetc.service.UserService;
import com.tjetc.utils.JwtUtil;
import com.tjetc.utils.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public Result login(UserDTO userDTO) {
        User user = userMapper.getByUsername(userDTO.getUsername());
        if (Objects.isNull(user)){
            return Result.error("用户名不存在");
        }
        if (!user.getPassword().equals(userDTO.getPassword())){
            return Result.error("密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getId());
        String token = JwtUtil.createToken(map);
        return Result.success(token);
    }

    @Override
    public Result register(UserDTO userDTO) {
        User user = userMapper.getByUsername(userDTO.getUsername());
        if (Objects.nonNull(user)){
            return Result.error("用户名已存在");
        }
        user = BeanUtil.copyProperties(userDTO, User.class);
        userMapper.insert(user);
        return Result.success();
    }
}
